<?php
// +----------------------------------------------------------------------
// | Tplay [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://tplay.pengyichen.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 听雨 < 389625819@qq.com >
// +----------------------------------------------------------------------


namespace app\admin\controller;

use \think\Db;
// use app\admin\model\News as NewsModel;//管理员模型
use app\admin\controller\Permissions;
class project extends Permissions
{
    /**
     * 产品列表
     * @return [type] [description]
     */
    public function index()
    {
        //产品类别
        $type = Db::name("project_type")->select();
        $this->assign('type',$type);

        $title=trim($this->request->Post('title'));
        $type_id=$this->request->Post('type_id');
        if($title !='') $where['p.title']= ['like','%' . $title . '%'];
        if($type_id !='') $where['p.type_id']= ['=',$type_id];
        //关联查询

        $join=[
            ["project_type t","p.type_id=t.id","LEFT"],
        ];
        if(empty($where)){
            $project=Db::name('project')->alias("p")->join($join)->field(["p.*","t.type"])->order(["p.sort"=>"desc","p.id"=>"desc"])->paginate(10);
        }
        elseif(!empty($where['p.title']) and empty($where['p.type_id'])){
            $project=Db::name('project')->where($where)->alias("p")->join($join)->field(["p.*","t.type"])->order(["p.sort"=>"desc","p.id"=>"desc"])->paginate(10,true,['query'=>request()->Post()]);
        }elseif(!empty($where['p.type_id'])){
            $project=Db::name('project')->where($where)->alias("p")->join($join)->field(["p.*","t.type"])->order(["p.type_sort"=>"asc","p.id"=>"desc"])->paginate(10,true,['query'=>request()->Post()]);
        }
        $this->assign('project',$project);
        // var_dump($news);
        return $this->fetch();
    }

    /**
     * 添加产品
     */
    public function add(){
        //实例化模型
        // $model=new NewsModel();
        $type=Db::name("project_type")->select();
        // var_dump($type);
        $this->assign('type',$type);
        //判断是不是操作数据库  
        if($this->request->isPost()){

            $post=$this->request->post();
            // return  $post;
            //验证  唯一规则： 表名，字段名，排除主键值，主键名

                $validate = new \think\Validate([
                    ['type_id', 'require', '产品类型必选!'],
                    ['type_sort', 'number', '排序格式不正确,请填数字'],
                    ['title', 'require', '产品标题必填!'],
                    ['subtitle', 'require', '产品副标题必填'],
                ]);
            //验证部分数据合法性
            if (!$validate->check($post)) {
                $this->error('提交失败：' . $validate->getError());
            }
            $id=$this->request->Post("id");

            if($id!=''){
                $old_img=Db::name("project")->where('id',$id)->find();
                 //获取表单上传文件 例如上传了001.jpg
                 $file = $this->request->file('file');
            if(!empty($file)){
                    $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads/file');
                if($info){
                    $file =$info->getSaveName();
                    @unlink($_SERVER['DOCUMENT_ROOT']."shanghai/public/uploads/file/".$old_img['file']);
                }else{
                    echo $file->getError();
                }
            }else{
                    $file=$old_img['file'];
            }

            $file1 = $this->request->file('img1');
            if(!empty($file1)){
                    $info1 = $file1->move(ROOT_PATH . 'public' . DS . 'uploads/project');
                if($info1){
                    $img1 =$info1->getSaveName();
                    @unlink($_SERVER['DOCUMENT_ROOT']."kuangjiatp5/public/uploads/project/".$old_img['img1']);
                }else{
                    echo $file1->getError();
                }
            }else{
                    $img1=$old_img['img1'];
            }
            $file2 = $this->request->file('img2');
            if(!empty($file2)){
                    $info2 = $file2->move(ROOT_PATH . 'public' . DS . 'uploads/project');
                if($info2){
                    $img2 =$info2->getSaveName();
                    @unlink($_SERVER['DOCUMENT_ROOT']."kuangjiatp5/public/uploads/project/".$old_img['img2']);
                }else{
                    echo $file2->getError();
                }
            }else{
                    $img2=$old_img['img2'];
            }
             $file3= $this->request->file('img3');
            if(!empty($file3)){
                    $info3 = $file3->move(ROOT_PATH . 'public' . DS . 'uploads/project');
                if($info3){
                    $img3 =$info3->getSaveName();
                    @unlink($_SERVER['DOCUMENT_ROOT']."kuangjiatp5/public/uploads/project/".$old_img['img3']);
                }else{
                    echo $file3->getError();
                }
            }else{
                    $img3=$old_img['img3'];
            }
            $file4 = $this->request->file('img4');
            if(!empty($file4)){
                    $info4 = $file4->move(ROOT_PATH . 'public' . DS . 'uploads/project');
                if($info4){
                    $img4 =$info4->getSaveName();
                    @unlink($_SERVER['DOCUMENT_ROOT']."kuangjiatp5/public/uploads/project/".$old_img['img4']);
                }else{
                    echo $file4->getError();
                }
            }else{
                    $img4=$old_img['img4'];
            }
            $file5 = $this->request->file('img5');
            if(!empty($file5)){
                    $info5 = $file5->move(ROOT_PATH . 'public' . DS . 'uploads/project');
                if($info5){
                    $img5 =$info5->getSaveName();
                    @unlink($_SERVER['DOCUMENT_ROOT']."kuangjiatp5/public/uploads/project/".$old_img['img5']);
                }else{
                    echo $file5->getError();
                }
            }else{
                    $img5=$old_img['img5'];
            }
            }else{
                $file = $this->request->file('file');
                if(!empty($file)){
                        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads/file');
                    if($info){
                        $file =$info->getSaveName();
                        @unlink($_SERVER['DOCUMENT_ROOT']."shanghai/public/uploads/file/".$old_img['file']);
                    }else{
                        echo $file->getError();
                    }
                }else{
                        $file='';
                }
                     //获取表单上传文件 例如上传了001.jpg
                $file1 = $this->request->file('img1');

                if(!empty($file1)){
                        $info1 = $file1->move(ROOT_PATH . 'public' . DS . 'uploads/project');
                    if($info1){
                        $img1 =$info1->getSaveName();
                        @unlink($_SERVER['DOCUMENT_ROOT']."kuangjiatp5/public/uploads/project/".$old_img['img1']);
                    }else{
                        echo $file1->getError();
                    }
                }else{
                    return $this->error("第一张图片必须添加");
                        $img1='';
                }
                $file2 = $this->request->file('img2');
                if(!empty($file2)){
                        $info2 = $file2->move(ROOT_PATH . 'public' . DS . 'uploads/project');
                    if($info2){
                        $img2 =$info2->getSaveName();
                        @unlink($_SERVER['DOCUMENT_ROOT']."kuangjiatp5/public/uploads/project/".$old_img['img2']);
                    }else{
                        echo $file2->getError();
                    }
                }else{
                        $img2='';
                }
                 $file3= $this->request->file('img3');
                if(!empty($file3)){
                        $info3 = $file3->move(ROOT_PATH . 'public' . DS . 'uploads/project');
                    if($info3){
                        $img3 =$info3->getSaveName();
                        @unlink($_SERVER['DOCUMENT_ROOT']."kuangjiatp5/public/uploads/project/".$old_img['img3']);
                    }else{
                        echo $file3->getError();
                    }
                }else{
                        $img3='';
                }
                $file4 = $this->request->file('img4');
                if(!empty($file4)){
                        $info4 = $file4->move(ROOT_PATH . 'public' . DS . 'uploads/project');
                    if($info4){
                        $img4 =$info4->getSaveName();
                        @unlink($_SERVER['DOCUMENT_ROOT']."kuangjiatp5/public/uploads/project/".$old_img['img4']);
                    }else{
                        echo $file4->getError();
                    }
                }else{
                        $img4='';
                }
                $file5 = $this->request->file('img5');
                if(!empty($file5)){
                        $info5 = $file5->move(ROOT_PATH . 'public' . DS . 'uploads/project');
                    if($info5){
                        $img5 =$info5->getSaveName();
                        @unlink($_SERVER['DOCUMENT_ROOT']."kuangjiatp5/public/uploads/project/".$old_img['img5']);
                    }else{
                        echo $file5->getError();
                    }
                }else{
                        $img5='';
                }
            }
            
            if($post['type_sort']==''){
                $type_sort=999;
            }else{
                $type_sort=$post['type_sort'];
            }
            $link=ltrim($post['link'],"http://");
            $data=[
                    'title'=>$post['title'],
                    'subtitle'=>$post['subtitle'],
                    'content'=>$post['content'],
                    'type_id'=>$post['type_id'],
                    'sort'=>$post['sort'],
                    'link'=>$link,
                    'img1'=>$img1,
                    'img2'=>$img2,
                    'img3'=>$img3,
                    'img4'=>$img4,
                    'img5'=>$img5,
                    'file'=>$file,
                    'read_num'=>0,
                    'type_sort'=>$type_sort,
                    "create_time"=>date("Y-m-d H:i:s")
                ];
               
            if($id==''){   
              
                $ress=Db::name('project')->insert($data);
                if($ress==false) return $this->error('保存失败');   
            }else{
                $data1=[
                    'title'=>$post['title'],
                    'subtitle'=>$post['subtitle'],
                    'content'=>$post['content'],
                    'type_id'=>$post['type_id'],
                    'link'=>$link,
                    'sort'=>$post['sort'],    
                    'img1'=>$img1,
                    'img2'=>$img2,
                    'img3'=>$img3,
                    'img4'=>$img4,
                    'img5'=>$img5,
                    'file'=>$file,
                    'type_sort'=>$type_sort,
                ];
                $res = Db::name('project')->where('id',$id)->update($data1);
                if($res==false) return $this->error('修改失败');     
            }
            return $this->success("产品保存成功",'admin/project/index');
        }elseif($this->request->has('id')){
            //获取对应数据id
            $id=$this->request->param("id");
            $project=Db::name("project")->where("id",$id)->find();   
            $this->assign("project",$project);
            return $this->fetch();
        }else{
            return $this->fetch();
        }
    }


     /**
     * 产品删除
     * @return [type] [description]
     */
    public function delete()
    {
        if($this->request->isAjax()) {
            $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            if(false == Db::name('project')->where('id',$id)->delete()) {
                return 1;
            } else {
                return 0;
            }
        }
    }


    /**
     * 产品类别
     * 
     */
    public  function project_type(){
        $type=Db::name("project_type")->order("id","desc")->paginate(10);
        $this->assign("type",$type);
        return $this->fetch("project/project_type");
    }

        /**
     * 添加产品类别
     */
    public function type_add(){
        //实例化模型
        // $model=new NewsModel();

        //判断是不是操作数据库  
        if($this->request->isPost()){

            $post=$this->request->Post();
            $id=$this->request->Post("id");
            if($id==''){       
                $id=Db::name('project_type')->insert($post);
                if($id==false) return $this->error('修改失败');   
            }else{
                $res =Db::name('project_type')->where('id',$id)->update($post);
                if($res==false) return $this->error('修改失败');     
            }
            return $this->success('产品保存成功','admin/project/project_type');
        }elseif($this->request->has('id')){
            $id=$this->request->param("id");
            $type=Db::name("project_type")->where("id",$id)->find();
            // var_dump($friendly);
            $this->assign("type",$type);
            return $this->fetch();
        }else{
            return $this->fetch();
        }
    }


         /**
     * 产品类别删除
     * @return [type] [description]
     */
    public function type_delete()
    {
        if($this->request->isAjax()) {
            $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            if(false == Db::name('project_type')->where('id',$id)->delete()) {
                return 1;
            } else {
                // addlog($id);//写入日志
                return 0;
            }
        }
    }

    /**
     * 产品阅读数量
     * @return [type] [description]
     */
    public function read_num(){
        //查询
        $title=trim($this->request->Post('title'));
        $start_time=strtotime($this->request->Post('start_time'));
        $end_time=strtotime($this->request->Post('end_time'));
        $where2=" and 1=1";
        if($start_time!='') $where2.=" and create_time >".$start_time;
        if($end_time!='') $where2.=" and create_time <".$end_time;

        if($title !='') $where1['title']= ['like','%'.$title.'%'];
        
        if($title !=''){
             $field=",(select count(*) from project_read where p_id=p.id ".$where2.") as num";
            $project_read = Db::name("project")->alias('p')->field("p.title".$field)->where($where1)->order("num","desc")->paginate(10);

        }else{
            $field=",(select count(*) from project_read where p_id=p.id ".$where2.") as num";
            $project_read = Db::name("project")->alias('p')->field("p.title".$field)->order("num","desc")->paginate(10);
        }

         // var_dump($result);
        $this->assign("project_read",$project_read);
        return $this->fetch();
    }


    /**
     * 产品咨询
     */
    public function consult(){
        //搜索条件

        $state=$this->request->Post('state');
        if($state !='') $where['state']= ['=',$state];
        $join=[
            ['project p','c.p_id=p.id','LEFT']
        ];
        $consult = empty($where)?Db::name("project_consult")->alias('c')->join($join)->field("c.*,p.title")->order("id","desc")->paginate(10):Db::name("project_consult")->alias('c')->join($join)->field("c.*,p.title")->where($where)->order("id","desc")->paginate(10,true,['query'=>request()->Post()]);
        $this->assign("consult",$consult);
        return $this->fetch();
    }



    /**
     * 产品咨询回复
     */
    public function consult_reply(){
        //判断是不是操作数据库  
        if($this->request->isPost()){
            $post=$this->request->post();
            $data=["reply"=>$post['reply'],"state"=>$post['state']];
            $res =Db::name('project_consult')->where('id',$post['id'])->update($data);
            if($res==false) return $this->error('修改失败');     
            return $this->success('产品咨询回复成功','admin/project/consult');
        }else{
            $id=$this->request->param("id");
            $consult=Db::name("project_consult")->where("id",$id)->find();
            // var_dump($friendly);
            $this->assign("consult",$consult);
            return $this->fetch();
        }
    }

    /**
     * 产品推荐
     */
    public function project_top(){
        $project_top = Db::name('project_top')->alias('t')->field(['t.sort,t.id,p.title'])->join([['project p','p.id=t.p_id','LEFT']])->order(['t.sort'=>"asc","t.id"=>"desc"])->paginate(10);
        $this->assign("project_top",$project_top);
        return $this->fetch();
    }


     /**
     * 产品推荐
     */
    public function top_add(){

        $top = Db::name('project')->order("id","desc")->select();
        $this->assign("top",$top);

        if($this->request->IsPost()){
            $id=$this->request->post('id');
            $post=$this->request->post();
            if($post['sort']==''){
                $post['sort']='999';
            }
            if($id!=''){
                $data=['sort'=>$post['sort'],'p_id'=>$post['p_id']];
                if(Db::name('project_top')->where('id',$id)->update($data)){
                    return $this->success('保存成功','admin/project/project_top');
                }else{
                    return $this->error('保存失败');
                }

            }else{
                if(Db::name('project_top')->insert($post)){
                    return $this->success('保存成功','admin/project/project_top');
                }else{
                    return $this->error('保存失败');
                }
                
            }
        }elseif($this->request->has('id')){
            //获取对应数据id
            $id=$this->request->param("id");
            $project_top = Db::name('project_top')->where('id',$id)->find();
            $this->assign("project_top",$project_top);
            return $this->fetch();
        }else{
            return $this->fetch();
        }     
    }

             /**
     * 产品推荐删除
     * @return [type] [description]
     */
    public function top_delete()
    {
        if($this->request->isAjax()) {
            $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            if(false == Db::name('project_top')->where('id',$id)->delete()) {
                return 1;
            } else {
                // addlog($id);//写入日志
                return 0;
            }
        }
    }
    
}
